package com.fishingwithme.domain.circle;

import com.fishingwithme.domain.anybiting.CircleMessageClient;
import com.fishingwithme.domain.anybiting.SubType;
import com.fishingwithme.infrastructure.dtos.anybiting.BaseCircleMessageDto;
import com.fishingwithme.infrastructure.dtos.circle.CircleHarvestShowDto;
import com.fishingwithme.infrastructure.dtos.circle.CircleNewSpotEventDto;
import com.fishingwithme.infrastructure.dtos.circle.CircleStatisticsRptDto;
import com.fishingwithme.infrastructure.mapper.circle.CircleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class CircleRedisMessageSubscriber implements MessageListener {

    @Autowired
    private CircleMessageClient client;

    @Autowired
    private CircleMapper circleMapper;

    @Autowired
    @Qualifier("circleRedisMsgTemplate")
    private RedisTemplate<String, Object> circleRedisMsgTemplate;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        BaseCircleMessageDto msg = (BaseCircleMessageDto) circleRedisMsgTemplate.getValueSerializer()
                .deserialize(message.getBody());
        assert msg != null;
        SubType subType = msg.getSubtype();
        switch (subType) {
            case EVT_N_SPOT -> {
                CircleNewSpotEventDto newSpot = circleMapper.selectNewSpot( msg.getBizId());
                newSpot.setId(msg.getBizId());
                msg.setContent(newSpot);
                client.saveMessage(msg);
            }
            case RPT_N_CIRCLE -> {
                CircleStatisticsRptDto dto = circleMapper.selectCircleStatistics(msg.getBizId());
                msg.setContent(dto);
                client.saveMessage(msg);
            }
            case EVT_SHOW_H -> {
                CircleHarvestShowDto dto = circleMapper.selectShowHarvest(msg.getBizId());
                if (dto != null) {
                    msg.setContent(dto);
                    client.saveMessage(msg);
                }
            }
            case EVT_ASK -> {
                //TODO: implement
                client.saveMessage(msg);
            }
        }
    }
}
